#!/usr/bin/env python3
"""
屏幕点击和输入工具 - 主程序入口
优化版本：模块化重构
"""

import tkinter as tk
from tkinter import messagebox  # 单独导入 messagebox
import sys
import os
import traceback

# 添加模块路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'core'))
sys.path.append(os.path.join(os.path.dirname(__file__), 'ui'))


def check_dependencies():
    """检查必要的依赖包是否已安装"""
    missing_deps = []

    # 检查核心依赖
    try:
        import PIL
    except ImportError:
        missing_deps.append("Pillow (图片处理)")

    try:
        import pyautogui
    except ImportError:
        missing_deps.append("pyautogui (自动化控制)")

    try:
        import pyperclip
    except ImportError:
        missing_deps.append("pyperclip (剪贴板操作)")

    try:
        import pandas
    except ImportError:
        missing_deps.append("pandas (Excel处理)")

    try:
        import openpyxl
    except ImportError:
        missing_deps.append("openpyxl (Excel文件读写)")

    try:
        import keyboard
    except ImportError:
        missing_deps.append("keyboard (键盘监听)")

    # 检查Windows特定依赖
    if sys.platform == "win32":
        try:
            import win32clipboard
        except ImportError:
            missing_deps.append("pywin32 (Windows剪贴板)")

    return missing_deps


def show_dependency_error(missing_deps):
    """显示依赖缺失错误"""
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口

    error_msg = "缺少必要的依赖包！\n\n请安装以下模块：\n"
    for dep in missing_deps:
        error_msg += f"• {dep}\n"

    error_msg += "\n安装命令：\n"
    error_msg += "pip install pillow pyautogui pyperclip pandas openpyxl pywin32 keyboard\n\n"
    error_msg += "或者运行 install_requirements.bat"

    # 直接使用 messagebox，不需要 tk.messagebox
    messagebox.showerror("依赖缺失", error_msg)
    root.destroy()


def main():
    """主程序入口"""
    try:
        # 检查依赖
        missing_deps = check_dependencies()
        if missing_deps:
            show_dependency_error(missing_deps)
            sys.exit(1)

        # 导入核心模块
        from ui.main_window import MainWindow
        from core.config_manager import ConfigManager

        # 创建配置管理器
        config_manager = ConfigManager()

        # 创建主窗口
        root = tk.Tk()
        app = MainWindow(root, config_manager)

        # 启动主循环
        root.mainloop()

    except Exception as e:
        print(f"程序启动失败: {e}")
        traceback.print_exc()

        # 显示错误对话框
        try:
            root = tk.Tk()
            root.withdraw()
            # 直接使用 messagebox
            messagebox.showerror("程序错误", f"程序启动失败：\n{str(e)}")
        except:
            pass

        sys.exit(1)


if __name__ == "__main__":
    main()